<script setup lang="ts">
import {createArray} from '~/utils';
import {ExcelDomain, ImportRecordVO} from "~/api/responseResult";

const formSize = ref('')
const props = defineProps<{
  sheetData: Array<ExcelDomain>,
  excelDomain: ExcelDomain,
  importRecordVO: ImportRecordVO
}>()

interface SelectSheetState {
  sheetName: string,
  excelDomain: ExcelDomain,
  loading: boolean,
}

const state: SelectSheetState = reactive({
  sheetName: '',
  excelDomain: {
    sheetName: '',
    maxColumn: 0,
    tableHead: [],
    tableData: [],
    listMap: [],
  },
  loading: false
})

const sheetChange = (val: string) => {
  state.sheetName = val
  props.sheetData.forEach( async item => {
    if (item.sheetName === val) {
      state.excelDomain = item
      // if (item.tableHead.length == 0) {
      //   // 去查询
      //   state.loading = true
      //   const res:Result<ExcelDomain> = await getSheetContent({importPid: props.importRecordVO.pid, sheetName: val})
      //   if (res.success) {
      //     state.excelDomain = res.data
      //     item.tableHead = res.data.tableHead
      //     item.maxColumn = res.data.maxColumn
      //     item.listMap = res.data.listMap
      //     item.tableData = res.data.tableData
      //   }
      //   state.loading = false
      // } else {
      //   state.excelDomain = item
      // }
    }
  })
}

const tableHeadLabel = (index: any) => {
  let label = '';
  state.excelDomain.tableHead.forEach(excelField => {
    if (excelField.column === index) {
      label = excelField.value
    }
  })
  return label;
}

const getExcelDomain = () => {
  return {...state.excelDomain}
}

sheetChange((props.excelDomain && props.excelDomain.sheetName) ? props.excelDomain.sheetName : props.sheetData[0].sheetName)

defineExpose({
  tableHeadLabel,
  formSize,
  createArray,
  getExcelDomain
})
</script>

<template>
  <div style="text-align: center;">
    <el-form
        label-width="120px"
        class="demo-ruleForm"
    >
      <el-form-item label="请选择工作表">
        <el-select style="width: 100%" v-model="state.sheetName" @change="sheetChange">
          <el-option
              v-for="excelDomain in sheetData"
              :key="excelDomain.sheetName"
              :label="excelDomain.sheetName"
              :value="excelDomain.sheetName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据预览">
        <el-table
            v-loading="state.loading"
            max-height="600"
            stripe
            border
            :data="state.excelDomain.listMap" style="width: 100%">
          <el-table-column
              min-width="200"
              v-for="index in createArray(state.excelDomain.maxColumn)"
              :prop="String(index)" :label="tableHeadLabel(index)"/>
        </el-table>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>

</style>
